package com.ktm.gecco.crawler.boche.pipeline;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.stereotype.Service;

import com.geccocrawler.gecco.pipeline.Pipeline;
import com.geccocrawler.gecco.request.HttpRequest;
import com.geccocrawler.gecco.scheduler.DeriveSchedulerContext;
import com.ktm.gecco.common.utils.PostHttp;
import com.ktm.gecco.crawler.boche.bean.BocheCarIndex;
import com.ktm.gecco.crawler.boche.bean.BocheCarIndexBean;

@Service
public class BocheCarIndexPipelines implements Pipeline<BocheCarIndex> {

    public static List<String> urls = new ArrayList<String>();

    @Override
    public void process(BocheCarIndex carIndex) {
        HttpRequest request=carIndex.getRequest();

        for(BocheCarIndexBean bean:carIndex.getCarindexList()){
            String nextUrl = bean.getHref();
//            SchedulerContext.into(request.subRequest(nextUrl));
            String url="http://bochewang.com.cn/Show/CheLiangList";

            String str = nextUrl.substring(nextUrl.indexOf("Index/"), nextUrl.indexOf("?t"));
            String paiMai = str.substring(nextUrl.indexOf("/")+1,str.length());
            String param = "id=1&page_size=0&orderField=%E6%8B%8D%E5%8D%96%E5%BC%80%E5%A7%8B%E6%97%B6%E9%97%B4&shiGuLeiXing=&cheLiangPinPai=&xuanZeXiLie=&province=&city=&paiMaiID="+paiMai;
            String result = PostHttp.sendPost(url, param);
            JSONObject jsonStr = new JSONObject(result);
            int totalSize = Integer.parseInt(jsonStr.get("TotalCount").toString());
            String param1 = "id=1&page_size="+totalSize+"&orderField=%E6%8B%8D%E5%8D%96%E5%BC%80%E5%A7%8B%E6%97%B6%E9%97%B4&shiGuLeiXing=&cheLiangPinPai=&xuanZeXiLie=&province=&city=&paiMaiID="+paiMai;
            String result1 = PostHttp.sendPost(url, param1);
            JSONObject jsonStr1 = new JSONObject(result1);

            JSONObject dataObject = new JSONObject("{Data:"+jsonStr1.get("Data").toString()+"}");

            JSONArray jsonArray = dataObject.getJSONArray("Data");
            for(int i=0;i<jsonArray.length();i++){
                JSONObject jsonObj = (JSONObject) jsonArray.get(i);
                String detailUrl = "http://bochewang.com.cn/Vehicle/CheDetail/"+jsonObj.get("ID");
                urls.add(detailUrl);
            }
        }
        //把所有抓取的Url放到list中，然后进入第一个匹配的详情页中，然后在详情页执行循环操作
        String urlstr =urls.get(0);
        DeriveSchedulerContext.into(request.subRequest(urlstr));
    }

}
